#!/usr/bin/env python

#################################################################################
#
# Copyright (c) 2006 Michigan State University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#################################################################################

#################################################################################
#
#	Author:
#		Nathan Collins <npcollins@gmail.com>
#
#################################################################################

import MySQLdb
from dbinter import *
from datetime import datetime
from PyLucene import Document, IndexSearcher, FSDirectory, QueryParser, StandardAnalyzer
import cgi
import re
import os
from terms import *
from history import *
from record import *
from oaicookie import *
from directory import *
from oaieditor import *
from auth import *
from util import *

# make strings web safe - old
def webs(unsafe):
	sgt = re.compile('>')
	slt = re.compile('<')
	safe = unsafe.encode('ascii', 'xmlcharrefreplace')
	safe = sgt.sub('&gt;',safe)
	safe = slt.sub('&lt;',safe)
	return safe

# the searcher class using db
class expander_db:
	def __init__(self):
		self.db = oai_db()

	def connect(self):
		try:
			self.db.connect()
			return 0
		except:
			print "Content-type:  text/html\n"
			print "<div class=\"innerwin\">"
			print "Record unavailble at this time.";
			return 1

	def termproc(self,terms):
		self.terms = terms

	def process_remember(self):
		rechash = getActiveHash()
		if rechash == '': return	# this shouldn't happen in theory
		query = "SELECT * FROM harvestSearch WHERE recHash = '%s';" % rechash

		# retrieve block of records from harvest table
		(fields, rows) = self.db.query(query)

		# if there are no results, indicate and return
		if fields is None:
			print "Content-type:  text/html\n"
			print "Record unavailble at this time.";
			return

		# yank out the field names
		dict_keys = [field[0] for field in fields]

		# process each row
		for row in rows:
			# stitch the keys and data together
			dict_row = dict(zip(dict_keys, row))

		# print out data
		print "Content-type:  text/html; charset=UTF-8\n"
		print "<div id='rememberwin' class='f_left'>"
		print_rec_remember(dict_row)
		print "</div>"
		printTabs()

	def process_search(self,rechash,divid,expanded):
		self.resnum = divid
		query = "SELECT * FROM harvestSearch WHERE recHash = '%s';" % rechash

		# retrieve block of records from harvest table
		(fields, rows) = self.db.query(query)

		# if there are no results, indicate and return
		if fields is None:
			print "Content-type:  text/html\n"
			print "Record unavailble at this time.";
			return

		# yank out the field names
		dict_keys = [field[0] for field in fields]

		# process each row
		for row in rows:
			# stitch the keys and data together
			dict_row = dict(zip(dict_keys, row))

		print "Content-type:  text/html; charset=UTF-8\n"
		if expanded:
			print_rec_expand(dict_row,self.terms,self.resnum)
		else:
			print_rec_short(dict_row,self.terms,self.resnum)

# main function
class ajax_main:
	def __init__(self):
		# string to return
		self.params = cgi.FieldStorage()

		# suggest directory browse
		if self.params.has_key('suggestdir'):
			self.suggestdir = self.params['suggestdir'].value
			print 'Content-type: text/html\n'
			printDirectory(self.suggestdir,1)
			return

		# rememeber results
		if self.params.has_key('remember'):
			self.remember = self.params['remember'].value
			
			self.luc = expander_db()
			if self.luc.connect():
				# db not up
				return

			self.luc.process_remember()
			return

		# editor approval/rejection
		if self.params.has_key('ar'):
			# approved or rejected
			self.ar = cui(self.params['ar'].value)
			# record for aproval/rejection
			self.r = cui(self.params['r'].value)

			# authenticate editor
			success, message = authenticate()

			# handle record
			print 'Content-type: text/html\n'
			if success == 1:
				print handleSuggest(self.r, self.ar)
			else:
				print '<b>FAILED:</b> %s' % message
			return
				

		# expanded result
		if self.params.has_key('expand'):
			self.expand = self.params['expand'].value
			self.resnum = self.params['r'].value
			self.terms = self.params['s'].value

			self.luc = expander_db()
			if self.luc.connect():
				# db not up
				return
			# term processing
			self.luc.termproc(self.terms)
			# return the info
			response = self.luc.process_search(self.expand,self.resnum,1)
			return

		# shrink result
		if self.params.has_key('shrink'):
			self.expand = self.params['shrink'].value
			self.resnum = self.params['r'].value
			self.terms = self.params['s'].value

			self.luc = expander_db()
			if self.luc.connect():
				# db not up
				return
			# term processing
			self.luc.termproc(self.terms)
			# return the info
			response = self.luc.process_search(self.expand,self.resnum,0)
			return

		# show search history
		if self.params.has_key('history'):
			self.history = self.params['history'].value
			print "Content-type:  text/html\n"
			showHistory()
			return


#eof

